package ycl.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 路由限流配置
 *
 * @author ycl
 * @date 2022/6/21 0021 18:09:00
 */
@Configuration
@Slf4j
public class GatewayConfig {

	private final List<RouteDefinition> routes;

	GatewayConfig(GatewayProperties properties) {
		this.routes = properties.getRoutes();
	}

	@PostConstruct
	public void init() {
		Set<GatewayFlowRule> rules = new HashSet<>();
		for (RouteDefinition r : routes)
			rules.add(getGatewayFlowRule(r.getId()));
		GatewayRuleManager.loadRules(rules);
	}


	private GatewayFlowRule getGatewayFlowRule(String resource) {
		return new GatewayFlowRule()
				//模式
				.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID)
				//gateway网关路由
				.setResource(resource)
				//流控类型
				.setGrade(RuleConstant.FLOW_GRADE_QPS)
				//间隔时间内最大请求次数
				.setCount(5)
				//设置间隔时间
				.setIntervalSec(1)
				//流控方式, 默认快速失败
				.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT)
				//超过最大请求次数时不再让任何请求通过
				.setBurst(0);
	}
}
